package com.company.common.server.config.mq.utils;

import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.mq.redis.client.message.RedisMQMessage;
import com.company.cloud.common.mq.redis.client.producer.RedisMQProducer;
import com.company.cloud.common.utils.SpringContextUtils;
import com.company.common.server.config.cloud.ProjectConfig;

import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.core.JmsMessagingTemplate;

import javax.jms.*;

public class SaasMqUtils {

    private final static Logger logger = LoggerFactory.getLogger(SaasMqUtils.class);

    /**
     * MQ发送消息
     * */
    public static boolean produce(String topic, String data, boolean isBroadcast, ProjectConfig projectConfig){
        return SaasMqUtils.produce(topic,data,0,isBroadcast,projectConfig);
    }
    /**
     * MQ发送消息
     * */
    public static boolean produce(String topic, String data,int effectTimeNum, boolean isBroadcast, ProjectConfig projectConfig){
        if(projectConfig.isActiveMqEnabled()){
            try {
                SaasMqUtils.produce2Active(topic,data,isBroadcast);
                return true;
            }catch (Exception e){
                logger.debug("++++Active MQ 发送消息错误:{}",e.getMessage());
                throw new BusinessException(BaseReturnEnum.MQ_Send_Error,"Active MQ 发送消息错误:"+e.getMessage());
            }
        }else if(projectConfig.isRedisMqEnabled()){
            try {
                SaasMqUtils.produce2redis(topic,data);
                return true;
            }catch (Exception e){
                logger.debug("++++Redis MQ 发送消息错误:{}",e.getMessage());
                throw new BusinessException(BaseReturnEnum.MQ_Send_Error,"Redis MQ 发送消息错误:"+e.getMessage());
            }
        }else{
            logger.debug("+++++ 未发送MQ消息【未配置MQ信息】");
            return false;
        }
    }





    public static void produce2Active(String topicName, String data ,boolean isBroadcast){
        JmsMessagingTemplate jmsMessagingTemplate=(JmsMessagingTemplate) SpringContextUtils.getBean("jmsMessageTemplate");
        if(isBroadcast){
            Topic topic=new ActiveMQTopic(topicName);
            jmsMessagingTemplate.convertAndSend(topic,data);
        }else{
            Queue queue = new ActiveMQQueue(topicName);
            jmsMessagingTemplate.convertAndSend(queue,data);
        }
    }


    public static void produce2redis(String topic, String data){
        RedisMQMessage message=new RedisMQMessage(topic,data);
        RedisMQProducer.getInstall().produce(message);
    }



}
